import axios from 'axios'

// axios静态配置
axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.baseURL = 'http://39.106.77.152:8888/financial'
// axios.defaults.baseURL = 'http://localhost:8888/financial'

// http request 拦截器
axios.interceptors.request.use(config => {
  return config
}, (err) => {
  return Promise.reject(err)
})

// http response 拦截器
axios.interceptors.response.use(res => {
  return res
}, (err) => {
  return Promise.reject(err)
})

// post
const post = function (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch(err => {
        reject(err)
      })
  })
}

// all
const all = arr => {
  return new Promise((resolve, reject) => {
    let req = []
    for (let item of arr) {
      req.push(axios.post(item.url, item.params))
    }
    axios.all(req)
      .then(axios.spread(() => {
        let resp = []
        for (let item of arguments) {
          resp.push(item)
        }
        resolve(resp)
      }))
      .catch(err => {
        reject(err)
      })
  })
}

export default {
  post: post,
  all: all
}
